package com.nxy.cpfsfe.busi.bolag;


import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.nxy.cpfsfe.enumtype.*;
import com.nxy.cpfsfe.mybatis.mapper.TbAMapper;
import com.nxy.cpfsfe.mybatis.mapper.TsPCmdMapper;
import com.nxy.cpfsfe.mybatis.pojo.TbA;
import com.nxy.cpfsfe.mybatis.pojo.TsPCmd;
import com.nxy.cpfsfe.service.CpfsService;
import com.nxy.cpfsfe.util.DateUtil;
import com.nxy.cpfsfe.util.RpcCommUtil;
import com.nxy.cpfsfe.util.StringUtil;
import com.nxy.cpfsfe.util.XmlUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;
import java.util.Map;

public class NCSNowDebitReceiptBean implements CpfsService {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(NCSNowDebitReceiptBean.class);
	SqlSession sqlSession = null;	
	
	/**
	 * 
	 * Description:异步处理实时借记回执
	 *
	 * @author
	 * @data 2019年8月24日
	 */
	
	public void  doService() {
		
		String tpId = DtaInfo.getInstance().getTpId();
		sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");		
		// 获取输入
		CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口
		// 业务报文			
		String bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
		LOGGER.info("接收到处理NCS借记回执输入BizMsg报文数据：[{}]" , bizMsg);
		//解包生成业务map
		Map map= xml2BizMap(bizMsg);
	    //云支付前置实时借记回执143.001.01报文
		if(!MsgCdOrTpEnum.MSGCD_143.getCode().equals((String)map.get("/transaction/header/msg/msgCd"))){
			LOGGER.warn("NCS借记回执报文标识号应为:[{}]，此报文标识号：[{}]非法",MsgCdOrTpEnum.MSGCD_143.getCode(),map.get("/transaction/header/msg/msgCd"));
			return;
		}
		try {				
			TbA tbA = queryOrgAgSeq(sqlSession, map);
			TsPCmd tsPCmd = queryOrgBizSeq(sqlSession, map);
			if(tbA!=null && tsPCmd!=null){
				map.put("updTm", DateUtil.getTimestamp(new Date()));	
				map.put("orgnBizSta",tbA.getBizSta());
				//更新业务流水交易状态
				sqlSession.getMapper(TsPCmdMapper.class).updateByMap(map);
				//更新账务流水交易状态
				sqlSession.getMapper(TbAMapper.class).updateByMap(map);
				LOGGER.info("账务流水表TbA和支付流水表tsPCmd更新数据成功chlSeqNo:{}",map.get("chlSeqNo"));
				if(!SysEcodeEnum.CPFS.getCode().equals(tbA.getSndSysId())){
					returnDebitReceipt(bizMsg,tbA.getSndSysId());
				}

			}else {
				LOGGER.error("原交易不存在chlSeqNo:" + map.get("chlSeqNo"));
			}
			
		}catch (Throwable e) {
			LOGGER.error("更新数据异常：业务流水表TbA和支付流水表tsPCmd：xSeqNo或chlSeqNo：["+map.get("xSeqNo")+"]。。。",e);
		}
							
	}
	
	//查询账务信息
	private TbA queryOrgAgSeq(SqlSession sqlSession,Map map) {
		TbAMapper tbAMapper = sqlSession.getMapper(TbAMapper.class);
		TbA tbA = new TbA();
		tbA.setCpfsSeqNo((String)map.get("cpfsSeqNo"));
		tbA.setAcqOrgId((String)map.get("acqOrgId"));
		TbA tbAResult = tbAMapper.query(tbA);	
				
		return tbAResult;

	}
	
	//查询支付信息
	private TsPCmd queryOrgBizSeq(SqlSession sqlSession,Map map) {	
		TsPCmdMapper tsPCmdMapper = sqlSession.getMapper(TsPCmdMapper.class);
		TsPCmd tsPCmd = new TsPCmd();	
		tsPCmd.setCpfsSeqNo((String)map.get("cpfsSeqNo"));
		tsPCmd.setAcqOrgId((String)map.get("acqOrgId"));
		TsPCmd tsPCmdResult = tsPCmdMapper.query(tsPCmd);
				
		return tsPCmdResult;

	}
	
	public void returnDebitReceipt(String bizMsg,String sndAppCd) {    
  	     String tpId = DtaInfo.getInstance().getTpId();
  	     String msgCd =XmlUtil.getValByXPath(bizMsg,"/transaction/header/msg/msgCd");
  		 
  		 EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", sndAppCd);
      	 EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", msgCd);
  	     EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg",bizMsg);
  	     RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	  
	     LOGGER.debug("rpc调用GW实时借记回执报文结束......");
  	     

	}
	
	
	
	public Map xml2BizMap (String bizMsg){
	    //拆解xml报文为map1
		Map<String, Object> map=null;
		try{
			Map xml2BizMap =XmlUtil.xml2Map(bizMsg);	
			//把map1<String, String>转换成map<String, Object>
			map =xml2BizMap; 
			LOGGER.debug("NCSNowDebitReceiptBean输入参数map开始：[{}]" ,map.toString());
	
			map = XmlUtil.formatXmlAttr(map,"AddtlInf");
			map.put("cpfsSeqNo",(String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId"));
			map.put("xSeqNo",(String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId"));
			map.put("chlSeqNo",(String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId"));
			map.put("respMsgTyp",(String)map.get("/transaction/header/msg/msgCd"));
			map.put("refMsgCd",(String)map.get("/transaction/header/msg/refMsgCd"));
			map.put("acqOrgId",(String)map.get("/transaction/header/msg/refSndMbrCd"));

			//不更新清算日期
			// String clrgD = (String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/StsRsnInf/SttlmDt");
			//map.put("clrgD", clrgD);
			String bizSts = (String)map.get("/transaction/body/FIToFIPmtStsRpt/OrgnlGrpInfAndSts/StsRsnInf/BizSts");
			String bizSta = StatEnum.BIZSTA_ING.getCode();//交易处理中;
			/*PR00：已清算 ---PR10：已补正
			PR01：已拒绝
			PR05：已付款
			*/
			if("PR00".equals(bizSts)||"PR05".equals(bizSts)){
				bizSta = StatEnum.BIZSTA_SUC.getCode();//交易成功
			}else if("PR01".equals(bizSts)){
				bizSta = StatEnum.BIZSTA_FAIL.getCode();//交易失败
			}else {
				bizSta = StatEnum.BIZSTA_ING.getCode();////交易处理中
			}
			map.put("bizSta",bizSta);
			map.put("respSta",bizSts);
			map.put("errCd", StringUtil.trimObject(map.get("/transaction/body/FIToFIPmtStsRpt/TxInfAndSts/StsRsnInf/Rsn/Prtry")));
			map.put("errDesc",StringUtil.trimObject(map.get("/transaction/body/FIToFIPmtStsRpt/TxInfAndSts/StsRsnInf/AddtlInf")));
			LOGGER.debug("NCSNowDebitReceiptBean输入参数map：[{}]" , map.toString());
			}catch (Throwable e){
				throw new BaseException(RespCd.NCPO0101,e,MsgCdOrTpEnum.MSGCD_143.getCode()+"报文解包异常");
			}
		return map;		
	}
	
	
}

